package com.wuneng.ircontrol.myUtil.update;

import android.app.Activity;
import android.app.DownloadManager;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.pm.PackageManager;
import android.database.Cursor;
import android.net.Uri;
import android.os.Build;
import android.support.v4.content.FileProvider;
import android.text.TextUtils;

import com.google.gson.reflect.TypeToken;

import java.io.File;
import java.util.HashMap;
import java.util.Map;

import com.wuneng.ircontrol.common.util.CariGson;
import com.wuneng.ircontrol.common.util.Constants;
import com.wuneng.ircontrol.myUtil.okhttp.OkPostListener;
import com.wuneng.ircontrol.myUtil.okhttp.OkServiceExecute;


/**
 * 自动更新工具类
 */
public class UpdateUtil {
    private static final String TAG = "UpdateUtil";
    //预留强制更新字段

    public static void checkUpdate(final Activity activity, final CheckUpdateCallback checkUpdateCallback) {


        Map map = new HashMap();
        map.put("versionCode", getVersionCode(activity) + "");
        map.put("deviceType", "Android");
        map.put("versionName", "offline");


        OkServiceExecute.getInstance().doPost("", map, new OkPostListener() {
            @Override
            public void onSuccess(String returnObject, String msg) {
                UpdateResBean resBean = CariGson.getInstance().fromJson(returnObject, new TypeToken<UpdateResBean>() {
                }.getType());

                if (resBean.isLastVersion()) {
                    if (checkUpdateCallback != null) {
                        checkUpdateCallback.onNoUpdate();
                    }
                } else {
                    checkUpdateCallback.downApk("http://" + Constants.SERVER.SERVER_IP + resBean.getUrl());
                }
            }

            @Override
            public void onError(String returnObject) {
                checkUpdateCallback.onCheckFail();
            }
        });

    }


    public static void download(Activity context, String url) {
        DownloadManager downloadManager = (DownloadManager) context.getSystemService(Context.DOWNLOAD_SERVICE);
        Uri uri = Uri.parse("http://" + Constants.SERVER.SERVER_IP + url);
        DownloadManager.Request request = new DownloadManager.Request(uri);
        request.setAllowedNetworkTypes(DownloadManager.Request.NETWORK_MOBILE | DownloadManager.Request.NETWORK_WIFI);

        request.setDestinationInExternalPublicDir("安全信息系统", "CariSecurity.apk");
        request.setDescription("安全信息系统新版本下载");
        request.setVisibleInDownloadsUi(true);
        request.setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED);
        request.setMimeType("application/vnd.android.package-archive");
        long id = downloadManager.enqueue(request);
        listener(context, id);
    }

    public static void doInstall(Context context, File apkFile) {
        Intent install = new Intent(Intent.ACTION_VIEW);
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
            install.setFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
            Uri apkUri = FileProvider.getUriForFile(context, "com.cari.bleTool.fileprovider", apkFile);
            install.setDataAndType(apkUri, "application/vnd.android.package-archive");
        } else {
            install.setDataAndType(Uri.fromFile(apkFile), "application/vnd.android.package-archive");
        }
        install.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        context.startActivity(install);
    }


    private static void listener(Activity context, final long Id) {
        // 注册广播监听系统的下载完成事件。
        IntentFilter intentFilter = new IntentFilter(DownloadManager.ACTION_DOWNLOAD_COMPLETE);
        BroadcastReceiver broadcastReceiver = new BroadcastReceiver() {
            @Override
            public void onReceive(Context context, Intent intent) {
                try {
                    long ID = intent.getLongExtra(DownloadManager.EXTRA_DOWNLOAD_ID, -1);
                    if (ID == Id) {
                        Intent install = new Intent(Intent.ACTION_VIEW);
                        File apkFile = queryDownloadedApk(context, Id);

                        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
                            install.setFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
                            Uri apkUri = FileProvider.getUriForFile(context, "com.cari.bleTool.fileprovider", apkFile);
                            install.setDataAndType(apkUri, "application/vnd.android.package-archive");
                        } else {
                            install.setDataAndType(Uri.fromFile(apkFile), "application/vnd.android.package-archive");
                        }
                        install.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                        context.startActivity(install);
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        };
        context.registerReceiver(broadcastReceiver, intentFilter);
    }

    private static File queryDownloadedApk(Context context, Long downloadId) {
        File targetApkFile = null;
        DownloadManager downloader = (DownloadManager) context.getSystemService(Context.DOWNLOAD_SERVICE);
        if (downloadId != -1) {
            DownloadManager.Query query = new DownloadManager.Query();
            query.setFilterById(downloadId);
            query.setFilterByStatus(DownloadManager.STATUS_SUCCESSFUL);
            Cursor cur = downloader.query(query);
            if (cur != null) {
                if (cur.moveToFirst()) {
                    String uriString = cur.getString(cur.getColumnIndex(DownloadManager.COLUMN_LOCAL_URI));
                    if (!TextUtils.isEmpty(uriString)) {
                        targetApkFile = new File(Uri.parse(uriString).getPath());
                    }
                }
                cur.close();
            }
        }
        return targetApkFile;
    }

    /**
     * 获取版本号名称
     *
     * @param context 上下文
     * @return
     */
    public static String getVerName(Context context) {
        String verName = "";
        try {
            verName = context.getPackageManager().
                    getPackageInfo(context.getPackageName(), 0).versionName;
        } catch (PackageManager.NameNotFoundException e) {
            e.printStackTrace();
        }
        return verName;
    }


    /**
     * 获取当前本地apk的版本
     *
     * @param mContext
     * @return
     */
    public static int getVersionCode(Context mContext) {
        int versionCode = 0;
        try {
            //获取软件版本号，对应AndroidManifest.xml下android:versionCode
            versionCode = mContext.getPackageManager().
                    getPackageInfo(mContext.getPackageName(), 0).versionCode;
        } catch (PackageManager.NameNotFoundException e) {
            e.printStackTrace();
        }
        return versionCode;


    }
}
